<template>
  <div></div>
</template>
<script>
import {getUserByToken, oauth2CallBack} from "../../request/api";
import {Message} from "_element-ui@2.15.6@element-ui";

export default {
  data() {
    return {

    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const query = this.$route.query;
      if(query.code !== undefined) {
        oauth2CallBack({code: query.code, redirect_uri: query.redirect_uri}).then(res=>{
          this.loading=false;
          if(res.code !== 0) {
            Message({
              showClose: true,
              message: res.msg,
              type: 'error'
            });
            this.$router.replace({
              path: '/login',
              query: {
                redirect_uri: query.redirect_uri
              }
            });
            return
          }
          getUserByToken({access_token: res.data.access_token}).then(res1=> {
            if (res1.code !== 0) {
              Message({
                showClose: true,
                message: res1.msg,
                type: 'error'
              });
              return
            }
            if (!res1.data) {
              Message({
                showClose: true,
                message: '用户获取失败',
                type: 'error'
              });
              return
            }
            localStorage.setItem('user', res1.data.name)
            localStorage.setItem('token', JSON.stringify(res.data))
            this.loading=false;
            this.$message({
              showClose: true,
              message: '登录成功',
              type: 'success'
            });
            this.$router.replace(query.redirect_uri);
          })

        })
            .catch(error => {

              console.log(error)
              this.loading=false;
              this.$message({
                showClose: true,
                message: '登录失败',
                type: 'error'
              });
              return error
            });
      }
    }
  }
}
</script>